#include "main.h"
#include "key.h"
#include "lib.h"
#include "oled.h"
#include "stm32f10x.h"
#include <stdio.h>
#include <string.h>

#include "Singly_linked_list.h"

#define PASSWD_LEN 10

// 用户界面
void userpage()
{
    OLED_Clear();
    OLED_ShowString(0, 2, "Login successful!");
    getch();
    return;
}

// 确认页面
// str：显示字符串
// 返回：Yes返回1，No或Esc返回0
char confirmpage(char* str)
{
    char flag = CH_NONE;
    OLED_Clear();
    OLED_ShowString(0, 2, str);
    OLED_ShowString(0, 4, "1.YES     2.NO");
    while (1) {
        flag = getch();
        if (flag == '1') {
            return 1;
        } else if (flag == '2' || flag == CH_ESC) {
            return 0;
        }
    }
}

// 添加密码页面
// pwlist：密码列表
// 返回：0添加失败，1添加成功
char addpwdpage(list* pwlist)
{
    char passwd[PASSWD_LEN+1] = "";
    char getstatus = 0;
    DATA data = { "", 0 };
    OLED_Clear();
    OLED_ShowString(0, 0, "Add passwd:");
    getstatus = ShowAndGets(0, 2, passwd);

    getch();

    if (getstatus == 0) {
        strcpy(data.string, passwd);
        data.num = list_len(*pwlist);
        if (list_append(pwlist, data) == true) {
            OLED_ShowString(0, 4, data.string);
            return 1;
        } else {
            return 0;
        }
        // OLED_ShowString(0, 4, passwd);
    }

    // 如果输入长度过长
    else if (getstatus == 1) {
        OLED_Clear();
        OLED_ShowString(0, 2, "length is too long");
        getch();
        return 0;
    } else {
        return 0;
    }
}

// 密码列表页面，可以添加和删除密码
// pwlist：密码列表
void pwdlistpage(list* pwlist)
{
    unsigned int i = 0;
    char item = 0;
    char item_max = 2;
    char ch = CH_NONE;
    char list_offset = 0;
    char str[PASSWD_LEN+10] = "";
    char ritem = 0;

    // 初始化item_max
    if (list_len(*pwlist) < 3) {
        item_max = list_len(*pwlist) % 3 - 1;
    } else {
        item_max = 2;
    }

    while (1) {

        OLED_Clear();
        OLED_ShowString(0, 0, "Passwd list:");

        // 打印
        for (i = 0; i < item_max + 1; i++) {
            if (i == item) {
                // sprintf(str, "%d| %s\0", list_offset+i+1, list_read(*pwlist, list_offset + i).string);
                sprintf(str, "%d| %s\0", list_offset+i+1, "******");

                OLED_ShowString_rev(0, i * 2 + 2, str);

            } else {
                // sprintf(str, "%d| %s\0", list_offset+i+1, list_read(*pwlist, list_offset + i).string);
                sprintf(str, "%d| %s\0", list_offset+i+1, "******");
                OLED_ShowString(0, i * 2 + 2, str);
            }
        }

        // 选中项*pwlist索引 = list_offset + item

        ch = getch();

        // 上方向键，且选中项不是首项
        if (ch == '2' && item > 0) {
            item--;

            // 下方向键，且选中项不是末尾项
        } else if (ch == '8' && item < item_max) {
            item++;

            // 上方向键，且选中项为首项，列表偏移量>0
        } else if (ch == '2' && item == 0 && list_offset > 0) {
            list_offset--;

            // 下方向键，且选中项为末尾项，且页面上至少有3项
        } else if (ch == '8' && item == item_max && item_max >= 2) {

            // 剩余的项数
            ritem = list_len(*pwlist) - list_offset;

            // 如果剩余项不足3项
            if (ritem < 3) {
                item_max = list_len(*pwlist) % 3 - 1;
            } else if (ritem != 3) {
                list_offset++;
            }

            // 删除键
        } else if (ch == CH_DEL) {
            if (list_len(*pwlist) <= 1) {
                OLED_Clear();
                OLED_ShowString(0, 2, "Only one pawwsd!");
                getch();
            } else if (confirmpage("Are you sure del it?")) {
                list_pop(pwlist, list_offset + item);
                list_offset = 0;
                item = 0;
                // 初始化item_max
                if (list_len(*pwlist) < 3) {
                    item_max = list_len(*pwlist) % 3 - 1;
                } else {
                    item_max = 2;
                }
            }

            // 添加键
        } else if (ch == CH_ADD) {
            addpwdpage(pwlist);
            list_offset = 0;
            item = 0;
            // 初始化item_max
            if (list_len(*pwlist) < 3) {
                item_max = list_len(*pwlist) % 3 - 1;
            } else {
                item_max = 2;
            }
            // 退出键
        } else if (ch == CH_ESC) {
            return;

            // 回车键
        } else if (ch == '\n') {
            OLED_ShowString(0, 0, "                ");
            OLED_ShowString(0, 0, list_read(*pwlist, list_offset + item).string);
            getch();
        }
    }
}

// 管理员页面
// apwlist：管理员密码列表
// upwlist：普通用户密码列表
void adminpage(list* apwlist, list* upwlist)
{
    if (loginpage(*apwlist, NULL)) {
        OLED_Clear();
        OLED_ShowString(0, 2, "Admin Login successful!");
        getch();
        pwdlistpage(upwlist);
        return;
    }
    return;
}

// 主页面
void mainpage()
{

    list user_pwlist = NULL;
    list_append(&user_pwlist, (DATA) { "654321", 1 });
    list_append(&user_pwlist, (DATA) { "666666", 2 });

    list admin_pwlist = NULL;
    list_append(&admin_pwlist, (DATA) { "666666", 1 });
    // list_append(&admin_pwlist, (DATA) { "55555", 2 });
    // list_append(&admin_pwlist, (DATA) { "55551", 12 });
    // list_append(&admin_pwlist, (DATA) { "55552", 2 });

    char ch = CH_NONE;
    while (1) {
        OLED_Clear();
        OLED_ShowString(0, 0, "Options:");
        OLED_ShowString(0, 2, "1. login");
        OLED_ShowString(0, 4, "2. admin");
        ch = getch();
        switch (ch) {
        case '1':
            loginpage(user_pwlist, userpage);
            break;
        case '2':
            adminpage(&admin_pwlist, &user_pwlist);
            break;
        default:
            OLED_ShowString(0, 6, "Press 1 or 2!");
            getch();
            break;
        }
    }
}

// 登录页面
// pwlist: 密码列表
// func：验证成功执行的函数
// 返回：验证成功返回1，ESC退出则返回0；
char loginpage(list pwlist, void (*sucfunc)(void))
{
    char overflow = 0;
    unsigned char i = 0;
    char passwd[PASSWD_LEN + 1] = "";
    char loginstatus = 0;
    OLED_Clear();
    OLED_ShowString(0, 0, "Your passwd:");
    while (1) {
        overflow = ShowAndGets(0, 2, passwd);

        getch();

        // 如果输入长度过长
        if (overflow == 1) {
            OLED_Clear();
            OLED_ShowString(0, 2, "length is too long");
            getch();
            OLED_Clear();
            OLED_ShowString(0, 0, "Enter again:");
            continue;
        }

        // ESC键被按下
        if (overflow == 2) {
            return 0;
        }

        // 遍历密码列表进行比对
        for (i = 0; i < list_len(pwlist); i++) {
            // 匹配密码
            if (strcmp(list_read(pwlist, i).string, passwd) == 0) {
                loginstatus = 1;
                break;
            }
        }

        if (loginstatus) {
            // 密码正确
            if (sucfunc != NULL) {
                sucfunc();
            }
            return 1;
        } else {
            // 密码错误
            OLED_Clear();
            OLED_ShowString(0, 2, "Wrong password!");
            getch();
            OLED_Clear();
            OLED_ShowString(0, 0, "Enter again:");
        }
        continue;
    }
}


void main(void)
{
    OLED_Init();
    Key_Init();
    OLED_Clear();

    mainpage();

    while (1) { }
}
